package 多线程;

/**
 * @
 * @date 2025/06/29
 */
public class ThreadLocalTest {

    /**
     * 虽然三个线程共享的一个 ThreadLocal ，但是线程属性 ThreadLocalMap 是单独的，key 都是同一个ThreadLocal对象，value 不同
     * 使用完成之后需要调用 remove() 方法
     * <p>
     * InheritableThreadLocal 父子线程可以传递一次，线程池会有问题
     */
    public static void main(String[] args) {
        Suv7 suv7 = new Suv7();

        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        for (int i1 = 0; i1 < 4; i1++) {
                            suv7.sale();
                        }
                        System.out.println(suv7.threadLocal);
                        System.out.println(suv7.threadLocal.get());
                    } finally {
                        suv7.threadLocal.remove();
                    }

                }
            }).start();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    static class Suv7 {

        ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

        private void sale() {
            threadLocal.set(threadLocal.get() + 1);
        }

    }

}
